<?php 
/**
 * Yjnic_Storage storage存储
 *
 * @package     Yjnic
 * @author      prettyyjnic <prettyyjnic@qq.com> 2015-11-27
 */

class Yjnic_Storage implements Yjnic_StorageInterface {
    private $_bucket = '';
    private $_base_path = '';

    public function __construct($configs){
        if (empty($configs)) 
            throw new Yjnic_Exception("Default bucket can not be empty", 501);
        if (!is_dir($configs['base_path'])) 
            throw new Yjnic_Exception("Base path can not access", 501);
        $this->_bucket = $configs['bucket'];
        $this->_base_path = rtrim( $configs['base_path'] , '/') ;
    }

    public function bucket($bucket){
        $this->_bucket = $bucket;
        return $this;
    }

    //读取一个Object，返回内容
    public function get($upload_name){
        $file_path = $this->_base_path .'/'. $this->_getFilePath($upload_name);
        if (!is_file($file_path)) return false;
        else return file_get_contents($upload_name);
    }

    /**
     * @param $file, 要上传的文件的路径
     * @param $upload_name , 保存的名字
     * @param $is_cover , 是否覆盖
     * @return 访问的路径
     */
    public function upload($file, $upload_name, $is_cover=false){
        if ($is_cover==false && $this->get($upload_name)) {
            throw new Yjnic_Exception("Upload file is exists", 400);  
        }
        // 创建文件夹
        $file_path = $this->_getFilePath($upload_name);
        $dir = dirname($file_path);
        if( !is_dir($dir) && !mkdir($dir, 0777, true)){
            throw new Yjnic_Exception("Can not make dir {$dir}", 400);
        }
        /* 移动文件 */
        if (!move_uploaded_file($file, $file_path)) {
            throw new Yjnic_Exception("Upload file Error", 401);
        }
        return $file_path;
    }

    //删除
    public function delete($upload_name){
        $file_path = $this->_getFilePath($upload_name);        
        if (!is_file($file_path)) {//文件不存在视为已删除
            return true;
        }
        return unlink($file_path);        
    }

    private function _getFilePath($upload_name){
        return $this->_base_path . '/' . $this->_bucket . '/' . $upload_name;
    }
}